package depts

import (
	"strings"

	"sieve_admin_server_userpass/pkg/cache"
	"sieve_admin_server_userpass/pkg/im3/db"
	"sieve_admin_server_userpass/pkg/log"
)

var (
	c    = cache.PeriodLoad(db.LoaderPeriod, loadList)
	dbok = false
)

func init() {
	db.OnConnected(func() {
		dbok = true
		c.Load()
	})
}

type Dept struct {
	Did    int
	Name   string
	Leader int
	Order  int
	Labels []string
	Unit   int
}

func loadList() (list []*Dept) {
	list = []*Dept{}
	if !dbok {
		return
	}
	rows, err := db.Mysql().Query("SELECT `Did`,`Name`,`Leader`,`Order`,`Labels`,`Unit` FROM `Dept` ORDER BY `Order` DESC,`Did`")
	if err != nil {
		log.Err(err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		d := &Dept{Labels: []string{}}
		var labels string
		if err := rows.Scan(
			&d.Did,
			&d.Name,
			&d.Leader,
			&d.Order,
			&labels,
			&d.Unit,
		); err != nil {
			log.Err(err)
			return
		}
		if len(labels) > 0 {
			d.Labels = strings.Split(labels, ",")
		}
		list = append(list, d)
	}
	return
}

func Reload() {
	c.Load()
}

func GetAll() []*Dept {
	return c.Get()
}

func Get(id int) *Dept {
	for _, d := range c.Get() {
		if d.Did == id {
			return d
		}
	}
	return nil
}

func GetDepts() []*Dept {
	list := []*Dept{}
	for _, d := range c.Get() {
		if d.Order > 0 {
			list = append(list, d)
		}
	}
	return list
}

func GetApps() []*Dept {
	list := []*Dept{}
	for _, d := range c.Get() {
		if d.Order == 0 {
			list = append(list, d)
		}
	}
	return list
}
